package cn.mastor.org.service.impl;

import cn.mastor.basic.service.impl.BaseServiceImpl;
import cn.mastor.org.domain.Department;
import cn.mastor.org.mapper.DepartmentMapper;
import cn.mastor.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public void batchDel(List<Long> ids) {
        departmentMapper.batchDel(ids);
    }
    @Override
    public List<Department> deptTree(){
        List<Department> all = departmentMapper.findAll();
        Map<Long,Department> parentMap = all.stream().collect(Collectors.toMap(Department::getId,e ->e));
        List<Department> result = new ArrayList<>();
        for (Department dept:all){
            if (null == dept.getParentId()){
                result.add(dept);
            }else {
                Department parent = parentMap.get(dept.getParentId());
                List<Department> children = parent.getChildren();
                children.add(dept);
            }
        }
        return result;
    }
    @Override
    public List<Department> LowDeper(Long id){
        List<Department> all = departmentMapper.findAll();
        Map<Long,Department> parentMap = all.stream().collect(Collectors.toMap(Department::getId,e ->e));
        List<Department> result = new ArrayList<>();
        for (Department dept:all){
            if (id == dept.getParentId()){
                Department byId = departmentMapper.findById(dept.getId());
                result.add(byId);
            }
        }
        return result;
    }
}
